<template>
  <van-nav-bar :title="t('pick.title')" left-arrow @click-left="onClickLeft" placeholder fixed />
  <scanning ref="skuCodeRef" @keydownEnter="handleScan" :placeholder="t('pick.pleaseScanningPickNo')" isFocus isReset clearable />
  <van-cell-group>
    <van-empty v-if="finished && pickList?.length <= 0" :description="t('noData')"/>
    <van-list v-else v-model:loading="loading" :finished="finished" :loading-text="t('loading')" :finished-text="t('noMoreData')" @load="onLoad" >
      <van-row class="p-5 van-hairline--surround" v-for="(item, i) in pickList" :key="i" @click="choose(item.pickId, item.pickNo)">
        <van-col span="12">{{ item.pickNo }}</van-col>
        <van-col class="text-right" span="12">{{ item.realPickNum + '/' + item.pickNum }}</van-col>
      </van-row>
    </van-list>
  </van-cell-group>
  <van-back-top />
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { getRequest, scanFail, scanSuccess } from "@/api";
import router from "@/router";
import Scanning from "@/views/components/Scanning/index.vue";
import { showFailToast } from "vant";
import { localStorage } from "@/utils/local-storage";
import { STORAGE_USER_DATA_KEY } from "@/stores/mutation-type";

const data = localStorage.get(STORAGE_USER_DATA_KEY)
const userData = ref({})
if (data) {
  userData.value = { ...data };
}

const { t } = useI18n();
const onClickLeft = () => history.back();

const pickList = ref([]);
const loading = ref(false);
const finished = ref(false);
const pageNum = ref(0);

const onLoad = () => {
  pageNum.value += 1;
  getRequest("/pick/page", { status: 0, pageSize: 20, pageNum: pageNum.value, pickedUser: userData.value['userId'] }).then(res => {
    pickList.value = pickList.value.concat(res.data.records)
    loading.value = false;
    if (res.data.current >= res.data.pages) {
      finished.value = true;
    }
  }).catch(() => {
    loading.value = false;
    finished.value = true;
  })
};

const handleScan = (pickNo: string) => {
  getRequest("/pick/page", { status: 0, pickNo: pickNo }).then(res => {
    if (res.data.records.length > 0) {
      scanSuccess();
      const pickId = res.data.records[0].pickId;
      router.push({
        name: 'PickOperate',
        query: {
          pickId,
          pickNo
        }
      });
    } else {
      showFailToast(t('pick.pickNotAvl'));
      scanFail();
    }
  }).catch(() => {
    scanFail();
  });
};

const choose = (pickId: string, pickNo: string) => {
  router.push({
    name: 'PickOperate',
    query: {
      pickId,
      pickNo
    }
  });
}
</script>

<style scoped lang="less">
:deep(.van-cell) {
  font-size: 1rem;
}

:deep(.van-nav-bar__title) {
  font-size: 1rem;
  font-weight: 500;
  color: white;
}

:deep(.van-nav-bar__content) {
  background: #1b82d2;
}

:deep(.van-nav-bar .van-icon) {
  color: white;
}
</style>
